﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.ComponentModel;

namespace OpenLightGroup.Common.Interactivity
{
    /// <summary>
    /// Changes the order in which IsChecked values cycle from: Indeterminate, False, True to: Indeterminate, True, False.
    /// </summary>
    [Description("Changes the order in which IsChecked values cycle from: Indeterminate, False, True to: Indeterminate, True, False.")]
    public class IsCheckedCycleCheckBoxBehavior
        : Behavior<CheckBox>
    {

        private bool? previousValue = null;

        #region Overrides
        /// <summary>
        /// Wires up event handlers to the CheckBox
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
            this.AssociatedObject.Click += new RoutedEventHandler(AssociatedObject_Click);
            
        }

        /// <summary>
        /// Removes event handlers from the AssociatedObject
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.Click -= AssociatedObject_Click;
        }

        #endregion

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            this.previousValue = this.AssociatedObject.IsChecked;
            this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
        }

        private void AssociatedObject_Click(object sender, RoutedEventArgs e)
        {

            if (this.previousValue.HasValue == false)
            {
                this.AssociatedObject.IsChecked = true;
            }
            else if (this.previousValue == true)
            {
                this.AssociatedObject.IsChecked = false;
            }
            else
            {
                if (this.AssociatedObject.IsThreeState)
                {
                    this.AssociatedObject.IsChecked = null;
                }
                else
                {
                    this.AssociatedObject.IsChecked = true;
                }
            }

            this.previousValue = this.AssociatedObject.IsChecked;


        }

        

    }
}
